import pulp

# 设置为最大化问题
minimize_problem = False

# 设置为整数变量
integer_variables = True

# 物品的数量和背包的容量
num_items = 10
backpack_capacity = 50

# 随机生成物品的重量和价值
import random

weights = [random.randint(1, 10) for _ in range(num_items)]
values = [random.randint(10, 100) for _ in range(num_items)]

# 设置问题类型
prob = pulp.LpProblem("Backpack_Problem", pulp.LpMaximize if not minimize_problem else pulp.LpMinimize)

# 定义决策变量，每个物品是否选择（0或1）
x = [pulp.LpVariable(f'x{i}', cat='Integer', lowBound=0, upBound=1) for i in range(num_items)]

# 定义目标函数：最大化总价值
prob += pulp.lpSum(values[i] * x[i] for i in range(num_items)), "Total_Value"

# 定义约束：总重量不能超过背包容量
prob += pulp.lpSum(weights[i] * x[i] for i in range(num_items)) <= backpack_capacity, "Total_Weight"

# 求解问题
prob.solve()

# 输出结果
print("Status:", pulp.LpStatus[prob.status])
print("Optimal solution (items to take):")
for i in range(num_items):
    if x[i].varValue == 1:
        print(f"Take item {i} (weight: {weights[i]}, value: {values[i]})")
print("Optimal value (max total value):", pulp.value(prob.objective))
